<template>
  <!-- 关键：key 强制重新挂载，100% 清空数据和校验 -->
  <el-dialog
      :key="dialogKey"
      v-model="dialogVisible"
      :title="modeTitle"
      width="600"
      :before-close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
    >
      <!-- 头像 -->
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            :disabled="isDisabled('avatar')"
            :readonly="isReadonly('avatar')"
            :show-file-list="false"
            action="http://localhost:8083/files/upload"
            :on-success="handleUploadSuccess"
        >
          <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="formData.username"
                :disabled="isDisabled('username')"
                :readonly="isReadonly('username')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="昵称" prop="nick">
            <el-input
                v-model="formData.nick"
                :disabled="isDisabled('nick')"
                :readonly="isReadonly('nick')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select
                v-model="formData.sex"
                :disabled="isDisabled('sex')"
                :readonly="isReadonly('sex')"
                style="width: 100%"
            >
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number
                v-model="formData.age"
                :disabled="isDisabled('age')"
                :readonly="isReadonly('age')"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-select
                v-model="formData.role"
                :disabled="isDisabled('role')"
                :readonly="isReadonly('role')"
                style="width: 100%"
            >
              <el-option label="超级管理员" :value="1" />
              <el-option label="普通用户" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
                v-model="formData.status"
                :disabled="isDisabled('status')"
                :readonly="isReadonly('status')"
                style="width: 100%"
            >
              <el-option label="审核通过" :value="1" />
              <el-option label="审核不通过" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="家庭住址" prop="address">
            <el-input
                v-model="formData.address"
                :disabled="isDisabled('address')"
                :readonly="isReadonly('address')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="个人简介" prop="introduce">
            <el-input
                type="textarea"
                v-model="formData.introduce"
                :disabled="isDisabled('introduce')"
                :readonly="isReadonly('introduce')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">{{ mode === 'info' ? '关闭' : '取消' }}</el-button>
      <el-button v-if="mode !== 'info'" type="primary" @click="submit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  dialogVisible: Boolean,
  mode: { type: String, default: 'add' },
  form: { type: Object, default: () => ({}) },

  /* 禁用字段 */
  disabledFields: { type: Array, default: () => [] },
  disabledInAdd:  { type: Array, default: () => [] },
  disabledInEdit: { type: Array, default: () => [] },
  disabledInInfo: { type: Array, default: () => [] },

  /* 只读字段 */
  readonlyFields: { type: Array, default: () => [] },
  readonlyInAdd:  { type: Array, default: () => [] },
  readonlyInEdit: { type: Array, default: () => [] },
  readonlyInInfo: { type: Array, default: () => [] }
})

const emit = defineEmits(['update:dialogVisible', 'submit-success'])

const loading = ref(false)
const formRef = ref()
const dialogKey = ref(0)

// 初始空模型
const emptyForm = {
  username: '',
  nick: '',
  sex: '',
  age: null,
  address: '',
  introduce: '',
  role: null,
  status: null,
  avatar: ''
}

const formData = reactive({ ...emptyForm })

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nick: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  address: [{ required: false, message: '请输入地址', trigger: 'blur' }],
  introduce: [{ required: false, message: '请输入简介', trigger: 'blur' }]
}

const modeTitle = computed(() =>
    props.mode === 'add' ? '新增用户' : props.mode === 'edit' ? '编辑用户' : '查看详情'
)

/* 禁用判断 */
const isDisabled = field =>
    props.disabledFields.includes(field) ||
    (props.mode === 'add' && props.disabledInAdd.includes(field)) ||
    (props.mode === 'edit' && props.disabledInEdit.includes(field)) ||
    (props.mode === 'info' && props.disabledInInfo.includes(field))

/* 只读判断 */
const isReadonly = field =>
    !isDisabled(field) && (
        props.readonlyFields.includes(field) ||
        (props.mode === 'add' && props.readonlyInAdd.includes(field)) ||
        (props.mode === 'edit' && props.readonlyInEdit.includes(field)) ||
        (props.mode === 'info' && props.readonlyInInfo.includes(field))
    )

/* 打开弹窗：重置 + 赋值 + 清空校验 */
watch(
    () => props.dialogVisible,
    async val => {
      if (val) {
        dialogKey.value += 1
        await nextTick()
        // 先重置为空，再覆盖外部数据
        Object.assign(formData, emptyForm, props.form || {})
        formRef.value?.clearValidate()
      }
    }
)

/* 关闭弹窗：统一清空 */
const resetForm = () => {
  Object.assign(formData, emptyForm)
  formRef.value?.resetFields()
  emit('update:dialogVisible', false)
}

const dialogVisible = ref(false)
watch(() => props.dialogVisible, v => (dialogVisible.value = v))
watch(dialogVisible, v => !v && resetForm())

const handleClose = () => resetForm()

const handleUploadSuccess = res => {
  formData.avatar = res.data
  ElMessage.success('上传成功')
}

const submit = () =>
    formRef.value.validate(valid => {
      if (valid) {
        emit('submit-success', { ...formData, mode: props.mode })
        resetForm()
      }
    })
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
</style>